# -*- coding: UTF-8 -*-
# Written by Mattias Baecklund 
# Skattebrottsenheten, Skatteverket 
# Tax Fraud Unit, Swedish Tax Agency 
# mailTo:mattias.baecklund@skatteverket.se 
# Phone: +46(0)10-5722880 
# Version: 2013-08-03 
#   
# Imports
import sqlite3
import tkinter
from tkinter.filedialog import * 
import os 
import datetime
import getopt
import sys

class simpleapp_tk(tkinter.Tk):
	#start function for the gui
	def __init__(self,parent):
		tkinter.Tk.__init__(self,parent)
		self.parent = parent
		self.opened = False
		self.initialize()
	# Initializetion function that will create the layout of the gui
	# creates radio buttons for choosing the source of the sqlite3 db.
	# input fields for db and result folder.
	def initialize(self):
		# The layout of the GUI
		self.grid()
		
		# The text field for the path to the database
		# and support variables
		self.entryVariable = tkinter.StringVar()
		self.entryVariable.set(database)
		self.entry = tkinter.Entry(self,textvariable=self.entryVariable)
		self.entry.grid(column=0,row=1,columnspan=2,sticky='EW')
		
		# The text field for the directory to put the
		# result and support variables
		self.destinationDirVariable = tkinter.StringVar()
		self.destinationDirVariable.set(destination)
		self.destinationDir = tkinter.Entry(self,textvariable=self.destinationDirVariable)
		self.destinationDir.grid(column=0,row=3,columnspan=2,sticky='EW')
		
		# The label above the database path text field
		self.labelVariable = tkinter.StringVar()
		self.labelVariable.set("Skriv in sökvägen till databasen")
		self.label = tkinter.Label(self,textvariable=self.labelVariable,anchor="w",fg="white",bg="blue")
		self.label.grid(column=0,row=0,columnspan=2,sticky='EW')
		
		# The Radio buttons for choosing what the source of sqlite3 db
		# and support variables
		self.v = tkinter.IntVar()
		self.radioYahooMejlAndroid = tkinter.Radiobutton(self,text="Yahoo Mejl (Android)",variable=self.v,value=1)
		self.radioYahooMejlAndroid.grid(column=3,row=0,sticky='W')
		self.radioYahooMejlIOS =  tkinter.Radiobutton(self,text="Yahoo Mejl (IOS)",variable=self.v,value=2)
		self.radioYahooMejlIOS.grid(column=3,row=1,sticky='W')
		self.radioOutlookMejlAndrioid = tkinter.Radiobutton(self,text="Outlook Mejl (Android)",variable=self.v,value=3)
		self.radioOutlookMejlAndrioid.grid(column=3,row=2,sticky='W')
		# self.radioMittTele2Android =  tkinter.Radiobutton(self,text="Mitt Tele2 (Android)",variable=self.v,value=4)
		# self.radioMittTele2Android.grid(column=3,row=3,sticky='W')
		self.radioQuizKampenAndroid = tkinter.Radiobutton(self,text="QuizKampen (Android)",variable=self.v,value=5)
		self.radioQuizKampenAndroid.grid(column=3,row=4,sticky='W')
		self.radioYahooMejlAndroid.select()
		
		# Button for browse after the database and support variables
		self.askopenfilenamebutton = tkinter.Button(self)
		self.askopenfilenamebutton["text"] = "Välj databas"
		self.askopenfilenamebutton["command"] = self.OnAskOpenFileNameButtonClick
		self.askopenfilenamebutton.grid(column=0,row=2)
		
		# Button for browse after the destination directory and support variables
		self.askdirectorybutton = tkinter.Button(self)
		self.askdirectorybutton["text"] = "Välj Dest. Dir."
		self.askdirectorybutton["command"] = self.OnAskDirectoryButtonClick
		self.askdirectorybutton.grid(column=0,row=5)
		
		# Button for starting the processing of the sqlite3 db and support variables
		self.button = tkinter.Button(self)
		self.button["text"] = "Process databas"
		self.button["command"] = self.ProcessDatabase
		self.button.grid(column=3,row=5)

	# ProcessDatabase(self)
	# ----------------------------------------------------------------------
	# Function that gets called when pressing the process databas button
	# checkes the radio button selection and calles diffrent functions based
	# on the selection there.
	# -----------------------------------------------------------------------
	# parameter N/A
	# Result N/A
	def ProcessDatabase(self):
		# a stores the result of the radio button selection
		a = self.v.get()
		if a == 1:
			self.title = "Yahoo Mejl (Android)"
			self.YahooMejlAndroid()
		elif a == 2:
			self.title = "Yahoo Mejl (IOS)"
			self.YahooMejlIOS()
		elif a == 3:
			self.title = "Outlook Mejl (Android)"
			self.OutlookMejlAndroid()
		# elif a == 4:
			# self.title = "MittTele2 (Android)"
			# self.MittTele2Android()
		elif a == 5:
			self.title = "QuizKampen (Android)"
			self.QuizKampenAndroid()
		else:
			print("Okänt värde")
					
		# Some extractions have multiple accounts in the same database
		# To solve that problem we need to create subfolders in the
		# destination directory and have to exclude there radio button 
		# value here so that we get the right amount of calles to createHtml
		if not (a == 3 or a == 1):
			self.createHtml()
		#print("done")

	# OnAskOpenFileNameButtonClick(self)
	# ------------------------------------------------------------------------
	# Function that gets called when pressing the 'välj databas' button
	# Pops up a open file dialog with the title 'Välj sqlite3 databas'
	# sets the return value of the dialog box to the text field for
	# sqlite3 database.
	# ------------------------------------------------------------------------
	# Parameter N/A
	# Result N/A
	def OnAskOpenFileNameButtonClick(self):
		databasefilename = askopenfilename(title="Välj sqlite3 databas")
		self.entryVariable.set(databasefilename)

	# OnAskDirectoryButtonClick(self)
	# ------------------------------------------------------------------------
	# Function that gets called when pressing the 'välj Dest. Dir.' button
	# Pops up a open directory dialog with the title 'Välj destinations katalog'
	# sets the return value of the dialog box to the text field for destination
	# directory.
	# ------------------------------------------------------------------------
	# Parameter N/A
	# Result N/A	
	def OnAskDirectoryButtonClick(self):
		destDirectory = askdirectory(title="Välj destinations katalog")
		self.destinationDirVariable.set(destDirectory)

	# CreateDestDir(self)
	# ------------------------------------------------------------------------
	# Function that creates two subdirectorys in the destination directory. 
	# One named html and the second named headers
	# ------------------------------------------------------------------------
	# Parameter extraDir	Some programs have multiple accounts in the same
	#						database this directory helps keep them seperate.
	#						Has to start with / for path seperation.
	# Result N/A
	# Side effects			Creates directorys
	def CreateDestDir(self,extraDir=''):
		os.makedirs(self.destinationDirVariable.get()+ extraDir +"/html/",exist_ok=True) # create the html
		os.makedirs(self.destinationDirVariable.get()+ extraDir +"/headers/",exist_ok=True) # and headers directory

	# CreateFileNameTuplet(self,rowid,subject)
	# ------------------------------------------------------------------------
	# Function that creates a filenamn tuple that is used to store and pass
	# filename information to diffrent function.
	# ------------------------------------------------------------------------
	# Parameter rowid 		unique id for each mail.
	# Parameter subject		The subject line of the email
	# Parameter extraDir	Some programs have multiple accounts in the same
	#						database this directory helps keep them seperate.
	#						Has to start with / for path seperation.
	# Result 	tuple		Consisting of (filenamebody,filnameheaders,subject,rowid). 	
	def CreateFileNameTuplet(self,rowid,subject,extraDir='',fileNameEnding0='.html',fileNameEnding1='.html'):
		filenamehtml  = self.destinationDirVariable.get()+extraDir+"/html/"+"mejl_" + str(rowid)+fileNameEnding0
		filenametxt   = self.destinationDirVariable.get()+extraDir+"/headers/"+"mejl_" + str(rowid)+fileNameEnding1 #".txt"
		filenametuple = (filenamehtml,filenametxt,subject,rowid)
		self.thelist.append(filenametuple)
		return filenametuple

	# insertSpace(self,content)
	# ------------------------------------------------------------------------
	# Function that walks through content and finds the longest string.
	# Then insert '&nbsp;' so that all strings in content will be equal in length
	# ------------------------------------------------------------------------
	# Parameter content 	tuple of strings that are going to be 'normalize'.
	# Result 	tuple		tuple with all string in content but all strings are
	#						equal in length and padded with '&nbsp;' at the end.
	def insertSpace(self,content):
		max = 0
		for string in content:
			temp = len(string)
			if temp > max:
				max=temp
		retstring = ()
		for string in content:
			# multiplicera med html character '&nbsp;' 
			retstring = retstring + ("&nbsp;"*((max - len(string))+1),)
			
		return self.combine(content,retstring,code=False)

	# combine(self,leftside,rightside,bold=False,newline=False,code=True)
	# -------------------------------------------------------------------------
	# function that combine two tuples of strings, number and None into one
	# tuple. The first tuple is called leftside and the second is called
	# rightside and they are combined in the following pattern:
	# first element of leftside is concatenated with the first element of
	# rightside and stored as the first element of the result tuple. All the
	# elements in the result tuple are strings.
	#
	# There formating paramters:
	# bold 		if true it will put all elements in the leftside inside
	# 			<B> leftside element </B>
	# 
	# newline	if true it will add a newline character (<br>) to the end of the
	# 			combinde string. Leftside rightside<br>
	# 
	# code		if true it will put the combined string between <code> </code>
	#			tags. <code>leftside rightside</code>
	# -------------------------------------------------------------------------
	# Assumptions:
	# The tuples passed to combine as leftside and rightside must be qequal
	# in length. len(leftside) == len(rightside) == len(result tuple)
	# -------------------------------------------------------------------------
	# Parameter	leftside	Tuple with strings that going to be the left part
	#						of the combined string.
	#						len(leftside) == len(rightside)
	#
	# Parameter	rightside	Tuple with a mix of strings, numbers and None.
	#						len(rightside) == len(leftside)
	#
	# Parameter	bold		If true will surround the leftside string with
	#						bold characters. Can't be used with code.
	#
	# Parameter	newline		If true will add a newline character at the end
	#						of the combined strings.
	#
	# Parameter	code		If true will surround the combinde string with
	#						code characters. Can't be used with bold.
	#
	# Result	tuple		A tuple with strings formated according to the
	#						bold, newline and code parameters.
	#						len(result) == len(leftside)
	#						len(result) == len(rightside)
	def combine(self,leftside,rightside,bold=False,newline=False,code=True):
		boldchar = ''
		boldendchar = ''
		newlinechar = ''
		codechar = ''
		codeendchar = ''
		
		if code is True:
			codechar = '<code>'
			codeendchar = '</code>'
		else:
			if bold is True:
				bold = '<B>'
				boldend = '</B>'				
		
		if newline is True:
			newlinechar = '<br>'
			
		return tuple((codechar + boldchar +"{0}"+boldendchar+"{1}"+codeendchar + newlinechar).format(x,y) for x,y in zip(leftside,rightside))

	# printToFile(self,filename,content)
	# ----------------------------------------------------------------------
	# Prints the content to a file with the filename and path stored in
	# filename
	# ----------------------------------------------------------------------
	# Parameter	filename the name and path to the file. It will be
	# Parameter	content
	# Result	N/A
	def printToFile(self,filename,content):
		#f = open(filename,"w",encoding='utf-8')
		f = open(filename,"w",encoding='utf-8')
		#f = open(filename,"w")
		for x in content:
			print(x,file=f)
		f.flush()
		f.close()

	
	# getCursor(self,setRowFactory=True)
	# -----------------------------------------------------------------------
	# Creates a database cursor to the database pointed out in the 
	# database text field. The default behavior is to set the row factory
	# to a sqlite3 row, that will make it possible to use the fields of the
	# database to access vaules.
	# -----------------------------------------------------------------------
	# Parameter	setRowFactory	Default value True. Variable will control if
	#							connections row factory will be set to 
	#							sqlite3.Row or if standard tuples should be
	#							returned.
	# Result	cursor			A database
	def getCursor(self,setRowFactory=True):
		if self.opened is not True:
			self.conn = sqlite3.connect(self.entryVariable.get())
			self.opened = True
		if setRowFactory is True:
			self.conn.row_factory = sqlite3.Row
		return self.conn.cursor()

	# generateIndexHtml(self)
	# -----------------------------------------------------------------------
	# Creates the index html page in the root of the destination page
	# -----------------------------------------------------------------------
	# Parameter		N/A
	# Result		N/A
	# Side effect	Creates a file.
	def generateIndexHtml(self,extraDir=''):
		filename = self.destinationDirVariable.get() +extraDir+ "/index.html"
		my_temp=("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\" \"http://www.w3.org/TR/html4/frameset.dtd\">","<HTML>","<HEAD>","<TITLE>" + self.title + "</TITLE>","</HEAD>","<FRAMESET cols=\"20%, 80%\">\n","<FRAMESET rows=\"100%\">","<FRAME src=\"index_test.html\" name=\"leftside\">","</FRAMESET>","<FRAMESET rows=\"70%, 30%\">","<FRAME src=\"html/mejl_1.html\" name=\"rightside\">","<FRAME src=\"headers/mejl_1.html\" name=\"header\">","</FRAMESET>","</FRAMESET>","</HTML>")
		self.printToFile(filename,my_temp)

	# createHtml(self)
	# -----------------------------------------------------------------------
	# Generates an html file with hyperlinks to all the e-mails html page.
	# Each hyperlink opens a e-mail body page and a header page in to seperat
	# Windows.
	# -----------------------------------------------------------------------
	# Parameter		N/A
	# Result		N/A
	# Side effect	Creates a file.
	def createHtml(self,extraDir=''):
		#print('DEBUG: ')
		#print(self.thelist)
		self.generateIndexHtml(extraDir)
		
		filename = self.destinationDirVariable.get() + extraDir + "/index_test.html"
		
		#skapa fluff före våra punkter
		towrite = ("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">","<html>","<head>","<meta content=\"text/html; charset=ISO-8859-1\" http-equiv=\"Content-Type\">","<title>index</title>","</head>","<body>","<ul>")
		
		rangelist = range(0,len(self.thelist))
		#print(rangelist)
		for i in rangelist:
			towrite = towrite + ("<li><a href=\""+ str(self.thelist[i][0]) +"\" target=\"rightside\" onclick=\"window.open('" + str(self.thelist[i][1]) +"','header')\">" + self.thelist[i][2] + "</a></li>\n",)

		#skapa fluff efter våra punkter
		towrite = towrite + ("</ul>","</body>","</html>")
		
		self.printToFile(filename,towrite)

	#    Android Apps                                                                                                         
	#       /\                     |                          |                                                             
	#      /  \                    |                          |                                                             
	#     /____\   |______    _____| |____   _____   *   _____|                                                                                   
	#    /      \  |     |   |     | |    | |     |  |  |     |                                                                     
	#   /        \ |     |   |_____| |      |_____|  |  |_____|
	
	def QuizKampenAndroid(self):
		self.thelist=[]
		c1 = self.getCursor()
		c2 = self.getCursor()
		konversations = list()
		self.CreateDestDir()
		user_id_dict = dict()
		i = 1
		
		# get the user id's from qk_messages and map them to usernames from users and games table
		# create a
		debugcounter=1
		for row in c1.execute('select distinct to_id, from_id from qk_messages'):
			# Make a dict of all the id's in the qk_messages
			# This is to make it easy to pretty print the chat files
			# The chat messages are stored with a to and from id.
			# The id's are can alternate but you still want them together because they are part of the same chat session
			print("Debug run # " + str(debugcounter))
			print(user_id_dict)
			print(row)
			debugcounter+=1
			temp = set() # We need a unorded datastructure to store the id's from the messages and that can be added to a list
			
			# First check the qk_users table to get the friends name
			r = c2.execute('select name from qk_users where id =' + str(row['to_id'])).fetchone()
			if r is not None:
				user_id_dict[row['to_id']]=r[0] # r is a tuple ('name',) and we only want the name so [0] to get that
				
			r = c2.execute('select name from qk_users where id =' + str(row['from_id'])).fetchone()
			if r is not None:
				user_id_dict[row['from_id']]=r[0] # r is a tuple ('name',) and we only want the name so [0] to get that
				
			# Second check the games table to get the name of the rest.
			r = c2.execute('select opponent_name from qk_games where opponent_id =' + str(row['to_id'])).fetchone()
			if r is not None:
				user_id_dict[row['to_id']]=r[0] # r is a tuple ('name',) and we only want the name so [0] to get that
			
			r = c2.execute('select opponent_name from qk_games where opponent_id =' + str(row['from_id'])).fetchone()
			if r is not None:
				user_id_dict[row['from_id']]=r[0] # r is a tuple ('name',) and we only want the name so [0] to get that
			
			temp.add(row['to_id'])
			temp.add(row['from_id'])
			
			if temp not in konversations:
				konversations.append(temp)
				
		# conversations should now contain a list of pair of id's that have chated with each other.
		self.thelist = []
		for chatpairs in konversations:
			# We use pairs of chat partners to get some order in the chats.
			# We handle the normal files on the chatpairs level to get one
			# chat conversation in each file
			# Need variables for the content of chatpairs because sets can't be access using indexing. 
			chatpairsElement0 = chatpairs.pop()
			chatpairsElement1 = chatpairs.pop()
			
			filenameTuple = self.CreateFileNameTuplet(i,"(chat " + str(i) + ") " + str(chatpairsElement0) + "   <--->   " + str(chatpairsElement1))
			i += 1
			
			chatContent = '' # accumilate the chat content into a string that can be written to the html file
			for row in c1.execute('select * from qk_messages where ( to_id = '+str(chatpairsElement0)+' and from_id = '+str(chatpairsElement1)+' ) or ( from_id = '+str(chatpairsElement0)+' and to_id = '+str(chatpairsElement1)+' ) order by id'):
				if row['to_id'] == chatpairsElement0: # html text should be red
					chatContent += "<p><font color=\"#0f0f0f\">" + str(row['datetime']) + "</font>  <font color=\"red\">" + row['text'] + "</font></p>"
				else: # html text should be blue
					chatContent += "<p><font color=\"#0f0f0f\">" + str(row['datetime']) + "</font>  <font color=\"blue\">" + row['text'] + "</font></p>"
				
				self.printToFile(filenameTuple[1],("<p><font color=\"blue\">" + str(user_id_dict.get(chatpairsElement0,chatpairsElement0)) + "</font></p>","<p><font color=\"red\">" + str(user_id_dict.get(chatpairsElement1,chatpairsElement1)) + "</font></p>"))
			
			# Time to write the chat to file
			self.printToFile(filenameTuple[0],(chatContent,))
			
		
	# def MittTele2Android(self):
		# self.thelist=[]
		# c = self.getCursor()
		# self.CreateDestDir()
		
		# for row in c.execute('select * from soapCache'):
			# print('DEBUG:')
			# print(row)
			# filenameTuple = self.CreateFileNameTuplet(row['id'],row['msisdn'],fileNameEnding0='.xml')
			# self.printToFile(filenameTuple[0],(row['response'],))
			
			# metadata = self.insertSpace(("id:","msisdn:","request:","dtm:"))
			# databasedata =(row['id'],row['msisdn'],row['request'],row['dtm'])
			
			# self.printToFile(filenameTuple[1],self.combine(metadata,databasedata,newline=True,code=True))

	# YahooMejlAndroid(self)
	# ------------------------------------------------------------
	# The main function for parsing out mails from the sqlite3
	# database that Yahoo Mail client for android uses to store
	# the mails in.
	# ------------------------------------------------------------
	# Parameter		N/A
	# Result		N/A
	# Side effects	Creates a number of files.
	def YahooMejlAndroid(self):
		c = self.getCursor()
		cAttachment = self.getCursor()
		cAccounts = self.getCursor()
		
		
		for account in cAccounts.execute('select * from accounts'):
			self.thelist=[]
			account_number = str(account['_id'])
			#Create an extra directory to separet the accounts
			extraDir = '/' + account['serverYid'] + '(' + account_number + ')'
			self.CreateDestDir(extraDir)
			
		
			for row in c.execute('select * from messages_'+account_number):
				if row['subject'] is not None:
					filenameTuple = self.CreateFileNameTuplet(row['_id'],"(email " + str(row['_id']) + ") " + row['subject'],extraDir)
				else:
					filenameTuple = self.CreateFileNameTuplet(row['_id'],"(email " + str(row['_id']) + ")",extraDir)
				
				# Skriv body:n till fil
				self.printToFile(filenameTuple[0],(row['body'],))
				
				received = ""
				sent = ""
				if row['received'] is not None:
					received = str(datetime.datetime.fromtimestamp(row['received'])) + "  (" + str(row['received']) + ")"
				if row['sent'] is not None:
					sent = str(datetime.datetime.fromtimestamp(row['sent'])) + "  (" + str(row['sent']) + ")"
				
				metadata = self.insertSpace(("Ämne:","Skickat från:","Återsänd till:","Mottagare:","Trolig mottagare:","Kopia till:","Hemlig kopia:","Utdrag:","Bilagor:","Vidarebefodrad:","Svarat:","Mottaget:","Skickat:"))
				databasedata = (row['subject'],row['fromSender'],row['reply_to'],row['toRecipients'],row['apparentlyto'],row['cc'],row['bcc'],row['snippet'],row['attachment'],row['forwarded'],row['replied'],received,sent)
				
				if row['attachment'] is 1:
					for attachmentRow in cAttachment.execute('select  _id,parent,_data,name,size,inline from attachments_'+ account_number +' where parent=?',(row['_id'],)):
						metadata = metadata + ("Filnamn:",)
						databasedata = databasedata + (attachmentRow['name'] + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + str(attachmentRow['size']) + ' bytes',)
					
				
				self.printToFile(filenameTuple[1],self.combine(metadata,databasedata,newline=True,code=True))
			self.createHtml(extraDir)

	# OutlookMejlAndroid(self)
	# ------------------------------------------------------------
	# The main function for parsing out mails from the sqlite3
	# database that Outlook.com Mail client for android uses to store
	# the mails in.
	# ------------------------------------------------------------
	# Parameter		N/A
	# Result		N/A
	# Side effects	Creates a number of files and directorys.
	def OutlookMejlAndroid(self):
		c = self.getCursor()
		cAttachment = self.getCursor()
		cAccounts = self.getCursor()
		#self.CreateDestDir()
		
		# There can be multiple accounts. Each account will create a directory
		for account in cAccounts.execute('select * from accounts'):
			self.thelist=[]
			#Create an extra directory to separet the accounts
			extraDir = '/' + account['name'] + '(' + str(account['account_id']) + ')'
			self.CreateDestDir(extraDir)
			
			# The main loop för extracting the mails.
			for row in c.execute('select f.name, e.* from emails e, folders f where e.folder_id=f._id and e.account_id=?', (account['account_id'],) ):
				# if row['subject'] is not None:
					# filenameTuple = self.CreateFileNameTuplet(row['_id'],"(email " + str(row['_id']) + ") " + row['subject'],extraDir)
				# else:
					# filenameTuple = self.CreateFileNameTuplet(row['_id'],"(email " + str(row['_id']) + ")",extraDir)
				filenameTuple = self.CreateFileNameTuplet(row['_id'],"(email " + str(row['_id']) + ")",extraDir)
				
				#print('DEBUG: filenametuple ' + str(filenameTuple))
				if row['html_body'] is not None:
					self.printToFile(filenameTuple[0],(row['html_body'],))
				else:
					self.printToFile(filenameTuple[0],(row['body'],))
				
				deliverytime = ''
				created = ''
				modefied = ''
				
				if row['delivery_time'] is not None:
					deliverytime = str(datetime.datetime.fromtimestamp(int(row['delivery_time'])/1000)) + "  (" + row['delivery_time'] + ")"
				if row['created'] is not None:
					created = str(datetime.datetime.fromtimestamp(row['created']/1000)) + "  (" + str(row['created']) + ")"
				if row['modified'] is not None:
					modefied = str(datetime.datetime.fromtimestamp(row['modified']/1000)) + "  (" + str(row['modified']) + ")"
				
				
				metadata =("Mapp:","Ämne:","Skickat från:","Skickat från epost:","Återsänd till:","Mottagare:","Kopia till:","Hemlig kopia:","Kvar av body","Utdrag:","Prioritet:","Oläst:","Skickat:","Skapat:","Ändrad:","Konversations id:","Konversations index:")
				databasedata = (row['name'],row['subject'],row['_from'],row['_from_email'],row['reply_to'],row['_to'],row['cc'],row['bcc'],row['missing_html_body'],row['preview'],row['importance'],row['is_unread'],deliverytime,created,modefied,row['conversation_id'],row['conversation_index'])
				
				if row['has_attachments'] is 1:
					#print('Has attachment')
					for attachmentRow in cAttachment.execute('select * from attachments where email_id = ?',(row['_id'],)):
						metadata = metadata + ("Filnamn:  ",)
						databasedata = databasedata + (attachmentRow['file_name'] + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + str(attachmentRow['size']) + ' bytes',)
				
				#print("debug: filenameTuple[1] = " + filenameTuple[1])
				
				self.printToFile(filenameTuple[1],self.combine(self.insertSpace(metadata),databasedata,newline=True,code=True))
			self.createHtml(extraDir)


# IOS Apps
	# | /¨¨¨¨¨¨\ /¨¨¨¨¨\                         
	# | |      | |     |      
	# | |      | |                     
	# | |      |  -----              
	# | |      |       |                    
	# | |      | |     |
	# | \______/ \_____/
	
	# YahooMejlIOS(self)
	# ------------------------------------------------------------
	# The main function for parsing out mails from the sqlite3
	# database that Yahoo Mail client for android uses to store
	# the mails in.
	# ------------------------------------------------------------
	# Parameter		N/A
	# Result		N/A
	# Side effects	Creates a number of files.
	def YahooMejlIOS(self):
		
		print("not implemented yet")
	
# The start of the program. It will create a new object of the GUI
# set the title and starts an event loop
if __name__ == "__main__":
	
	# code for setting database and destination directory with parameters mostly for simple testing.
	database = ''
	destination = ''
	optlist, arguments = getopt.getopt(sys.argv[1:],'',['database=','destination='])
	for opt in optlist:
		if opt[0] == "--database":
			database=opt[1]
		if opt[0] == "--destination":
			destination=opt[1]
			
	app = simpleapp_tk(None)
	app.title('Sqlite3 parser for apps')
	app.mainloop()